
package net.yunxinyong.cec.filter;

import net.yunxinyong.cec.utils.CecException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author ttbf
 * @describe
 * @date 2018/7/10
 */

public class RequestFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(RequestFilter.class);

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain){
        WrappedHttpServletRequest httpServletRequest = new WrappedHttpServletRequest((HttpServletRequest) servletRequest);
        //HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;


        try {
            if (httpServletRequest.getRequestURI().contains("/cec/passport")) {
                filterChain.doFilter(httpServletRequest, servletResponse);
                return;
            }
            if (httpServletRequest.getRequestURI().contains("/cec/area")) {
                filterChain.doFilter(httpServletRequest, servletResponse);
                return;
            }

            checkLogin(httpServletRequest, httpServletResponse);
            filterChain.doFilter(httpServletRequest, servletResponse);
        } catch (CecException cecException){

        }catch (Exception e) {
            try {
                httpServletResponse.sendRedirect("/cec/index/error");
            } catch (IOException ignored) {
            }
        }
    }

    @Override
    public void destroy() {
    }



/**
     * 检查是否登陆
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws IOException
     * @throws ServletException
     */

    private void checkLogin(WrappedHttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {

        String cecId = httpServletRequest.getHeader("cecId");

        if (StringUtils.isBlank(cecId)) {
            httpServletResponse.sendRedirect("/cec/index/error");
            return;
        }
        String cecIdC = null;
        Cookie[] cookies = httpServletRequest.getCookies();
        for (Cookie cookie : cookies) {
            if ("cecId".equals(cookie.getName())) {
                cecIdC = cookie.getValue();
                continue;
            }

            if (!StringUtils.isBlank(cecIdC)) {
                break;
            }
        }
        if (!cecId.equals(cecIdC)) {
            httpServletResponse.sendRedirect("/tianjibian/index/error");
            return;
        }


    }

}

